package com.powervision.thirdlogindemo.utils

import android.app.Activity
import android.content.Intent
import android.util.Log
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.powervision.thirdlogindemo.utils.Constant.Companion.mGoogleRequestCode

/**
 * @auth: njb
 * @date: 2021/10/25 10:08
 * @desc: google登录工具类
 */
open class GoogleLoginUtils(
    private val activity: Activity,
    private var mGoogleLoginListener: GoogleLoginListener
) {
    val requestCode by lazy { mGoogleRequestCode }

    private var mGoogleSignInClient: GoogleSignInClient? = null

    /**
     * 初始化google登录
     *
     */
    init {
        val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build()
        mGoogleSignInClient = GoogleSignIn.getClient(activity, gso)
    }

    /**
     * 用户登录
     */
    fun signIn() {
        val signInClient: Intent? = mGoogleSignInClient?.signInIntent
        activity.startActivityForResult(signInClient, requestCode)
    }

    /**
     * 用户登录回调
     */
    fun handleSignInResult(mGoogleSignAccount: Task<GoogleSignInAccount>) {
        val account: GoogleSignInAccount? = mGoogleSignAccount.getResult(ApiException::class.java)
        val status: Task<GoogleSignInAccount> = mGoogleSignAccount
        try {
            if (status.isSuccessful) {
                if (account != null) {
                    mGoogleLoginListener.googleLoginSuccess(account)
                    Log.d("account", account.account.toString())
                } else {
                    mGoogleLoginListener.googleLoginFail("登录失败")
                }
            }
        } catch (e: ApiException) {
            e.printStackTrace()
            Log.d("signInResult:failed", e.statusCode.toString())
        }
    }

    open fun setGoogleSignListener(googleSignListener: GoogleLoginListener) {
        this.mGoogleLoginListener = googleSignListener
    }

    interface GoogleLoginListener {
        fun googleLoginSuccess(account: GoogleSignInAccount)
        fun googleLoginFail(message: String?)
        fun googleLogoutSuccess()
        fun googleLogoutFail()
    }
}